<template>
  <div class="weather-container">
    <div class="weather-background">
      <div class="clouds">
        <div class="cloud cloud1"></div>
        <div class="cloud cloud2"></div>
        <div class="cloud cloud3"></div>
      </div>
    </div>

    <el-card class="weather-card">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <div class="weather-icon">🌤️</div>
            <h2>全国天气预报</h2>
          </div>
          <div class="header-actions">
            <el-button
                @click="showNotificationDialog = true"
                type="warning"
                size="small"
                class="notification-btn"
            >
              <el-icon><Bell /></el-icon>
              创建通知
            </el-button>
            <el-button @click="refreshWeather" :loading="loading" type="primary" size="small" class="refresh-btn">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <!-- 城市选择 -->
      <div class="city-selector">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-input
                v-model="searchCity"
                placeholder="🔍 搜索城市"
                @keyup.enter="searchCityWeather"
                clearable
                class="search-input"
            >
              <template #append>
                <el-button @click="searchCityWeather" :loading="loading" class="search-btn">
                  <el-icon><Search /></el-icon>
                </el-button>
              </template>
            </el-input>
          </el-col>
          <el-col :span="12">
            <el-select
                v-model="selectedCity"
                placeholder="📍 选择城市"
                @change="getWeatherByCity"
                style="width: 100%"
                class="city-select"
            >
              <el-option
                  v-for="city in popularCities"
                  :key="city.adcode"
                  :label="city.name"
                  :value="city.adcode"
              />
            </el-select>
          </el-col>
        </el-row>
      </div>

      <!-- 当前天气 -->
      <div class="current-weather" v-if="currentWeather">
        <div class="weather-main">
          <div class="location-info">
            <div class="location-icon">📍</div>
            <h3>{{ currentWeather.city }}</h3>
            <p class="update-time">🕐 更新时间: {{ formatTime(currentWeather.reporttime) }}</p>
          </div>
          <div class="temperature-section">
            <div class="weather-icon-large">{{ getWeatherIcon(currentWeather.weather) }}</div>
            <div class="current-temp">{{ currentWeather.temperature }}°C</div>
            <div class="weather-desc">{{ currentWeather.weather }}</div>
            <div class="temp-range" v-if="forecast.length > 0">
              <span class="low-temp">❄️ {{ forecast[0].nighttemp }}°C</span>
              <span class="temp-separator">/</span>
              <span class="high-temp">🔥 {{ forecast[0].daytemp }}°C</span>
            </div>
          </div>
        </div>

        <!-- 天气预警 -->
        <div class="weather-alerts" v-if="weatherAlerts.length > 0">
          <div class="alert-item" v-for="alert in weatherAlerts" :key="alert.type">
            <el-alert
                :title="alert.title"
                :type="alert.alertType"
                :closable="false"
                show-icon
                class="weather-alert-item"
            >
              <template #default>
                <p>{{ alert.message }}</p>
              </template>
            </el-alert>
          </div>
        </div>

        <!-- 高温警告 -->
        <div class="weather-alert" v-if="isHighTemperature">
          <el-alert
              title="🌡️ 高温警告"
              type="warning"
              :closable="false"
              show-icon
              class="high-temp-alert"
          >
            <template #default>
              <p>当前温度较高，请注意防暑降温，避免长时间户外活动。</p>
            </template>
          </el-alert>
        </div>

        <!-- 天气详情 -->
        <div class="weather-details">
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="detail-item">
                <div class="detail-icon">💧</div>
                <div class="detail-label">湿度</div>
                <div class="detail-value">{{ currentWeather.humidity }}%</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="detail-item">
                <div class="detail-icon">🌬️</div>
                <div class="detail-label">风向</div>
                <div class="detail-value">{{ currentWeather.winddirection }}</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="detail-item">
                <div class="detail-icon">💨</div>
                <div class="detail-label">风力</div>
                <div class="detail-value">{{ currentWeather.windpower }}级</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="detail-item">
                <div class="detail-icon">👁️</div>
                <div class="detail-label">能见度</div>
                <div class="detail-value">{{ currentWeather.visibility }}km</div>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>

      <!-- 五天天气预报 -->
      <div class="forecast-section" v-if="forecast.length > 0">
        <div class="forecast-header">
          <div class="forecast-icon">📅</div>
          <h3>五天天气预报</h3>
        </div>
        <div class="forecast-container">
          <div class="forecast-item" v-for="(day, index) in forecast" :key="index">
            <div class="forecast-date">
              <div class="date-icon">📆</div>
              {{ formatDate(day.date) }}
            </div>
            <div class="forecast-weather-icon">{{ getWeatherIcon(day.dayweather) }}</div>
            <div class="forecast-weather">{{ day.dayweather }}</div>
            <div class="forecast-temp-range">
              <span class="forecast-high">🔥 {{ day.daytemp }}°C</span>
              <span class="forecast-low">❄️ {{ day.nighttemp }}°C</span>
            </div>
            <div class="forecast-wind">🌬️ {{ day.daywind }} {{ day.daypower }}级</div>
            <!-- 天气预警 -->
            <div class="forecast-alert" v-if="getDayWeatherAlert(day)">
              <el-tag :type="getDayWeatherAlert(day).alertType" size="small" class="weather-alert-tag">
                {{ getDayWeatherAlert(day).icon }} {{ getDayWeatherAlert(day).title }}
              </el-tag>
            </div>
            <!-- 高温警告 -->
            <div class="forecast-alert" v-if="parseInt(day.daytemp) >= 35">
              <el-tag type="danger" size="small" class="high-temp-tag">🌡️ 高温</el-tag>
            </div>
          </div>
        </div>
      </div>

      <!-- 错误提示 -->
      <el-alert
          v-if="error"
          :title="error"
          type="error"
          :closable="false"
          show-icon
          style="margin-top: 20px"
      />
    </el-card>

    <!-- 创建通知对话框 (新样式) -->
    <el-dialog
        v-model="showNotificationDialog"
        width="600px"
        :close-on-click-modal="false"
        @close="resetNotificationForm"
        class="create-notification-dialog"
        :show-close="true"
    >
      <el-form :model="notification" label-position="top" ref="notificationFormRef" class="notification-form-styled">
        <el-form-item label="配送员ID" prop="deliverymanId" :rules="{ required: true, message: '请输入配送员ID', trigger: 'blur' }">
          <el-input-number v-model="notification.deliverymanId" :min="1" controls-position="right" placeholder="输入目标配送员的ID" style="width: 100%;">
            <template #prefix><el-icon><User /></el-icon></template>
          </el-input-number>
        </el-form-item>

        <el-form-item label="通知类型" prop="type" :rules="{ required: true, message: '请选择通知类型', trigger: 'change' }">
          <el-select v-model="notification.type" placeholder="请选择通知类型" style="width: 100%;">
            <template #prefix><el-icon><Bell /></el-icon></template>
            <el-option label="天气提醒" value="weather">
              <span style="display: flex; align-items: center;"><el-icon style="margin-right: 8px;"><Sunny /></el-icon>天气提醒</span>
            </el-option>
            <el-option label="新订单提醒" value="new_order">
              <span style="display: flex; align-items: center;"><el-icon style="margin-right: 8px;"><ShoppingCart /></el-icon>新订单提醒</span>
            </el-option>
            <el-option label="系统通知" value="system">
              <span style="display: flex; align-items: center;"><el-icon style="margin-right: 8px;"><Cpu /></el-icon>系统通知</span>
            </el-option>
            <el-option label="收入提醒" value="earnings">
              <span style="display: flex; align-items: center;"><el-icon style="margin-right: 8px;"><Money /></el-icon>收入提醒</span>
            </el-option>
            <el-option label="任务更新" value="task_update">
              <span style="display: flex; align-items: center;"><el-icon style="margin-right: 8px;"><List /></el-icon>任务更新</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="通知标题" prop="title" :rules="{ required: true, message: '请输入通知标题', trigger: 'blur' }">
          <el-input v-model="notification.title" placeholder="可自定义通知标题">
            <template #prefix><el-icon><EditPen /></el-icon></template>
          </el-input>
        </el-form-item>

        <el-form-item
            v-if="isRelatedEntityIdVisible"
            label="关联实体ID"
            prop="relatedEntityId"
            :rules="{ required: true, message: '请输入关联的订单或任务ID', trigger: 'blur' }"
        >
          <el-input v-model="notification.relatedEntityId" placeholder="例如: 订单ID或任务包ID">
            <template #prefix><el-icon><Link /></el-icon></template>
          </el-input>
        </el-form-item>

        <el-form-item label="通知内容" prop="message" :rules="{ required: true, message: '请输入通知内容', trigger: 'blur' }">
          <el-input
              v-model="notification.message"
              type="textarea"
              :rows="4"
              placeholder="请输入具体的通知内容"
          >
            <template #prefix><el-icon><ChatDotRound /></el-icon></template>
          </el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer-styled">
          <el-button @click="showNotificationDialog = false" class="cancel-btn">
            <el-icon><Close /></el-icon>
            <span>取消</span>
          </el-button>
          <el-button @click="sendNotification" type="primary" :loading="sendingNotification" class="send-btn">
            <el-icon><Promotion /></el-icon>
            <span>立即发送</span>
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 通知预览对话框 -->
    <el-dialog
        v-model="showPreviewDialog"
        title="📱 通知预览"
        width="500px"
    >
      <div class="preview-content">
        <div class="preview-header">
          <div class="preview-icon">🚨</div>
          <div class="preview-title">{{ notificationForm.title }}</div>
        </div>
        <div class="preview-message">
          {{ previewMessage }}
        </div>
        <div class="preview-info">
          <p><strong>预警类型：</strong>{{ getAlertTypesText(notificationForm.alertTypes) }}</p>
          <p><strong>目标区域：</strong>{{ getDeliveryAreasText(notificationForm.deliveryAreas) }}</p>
          <p><strong>通知方式：</strong>{{ getNotificationMethodsText(notificationForm.notificationMethods) }}</p>
          <p><strong>紧急程度：</strong>{{ getPriorityText(notificationForm.priority) }}</p>
          <p><strong>发送时间：</strong>{{ getSendTimeText(notificationForm.sendTime, notificationForm.scheduledTime) }}</p>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh, Search, Bell, Sunny, ShoppingCart, Cpu, Money, List, EditPen, Link, Promotion, User, Close, ChatDotRound } from '@element-plus/icons-vue'

// 高德API密钥
const AMAP_KEY = 'd93428c62f0f8fcbcbe1be9e05893e41'

// 响应式数据
const loading = ref(false)
const error = ref('')
const searchCity = ref('')
const selectedCity = ref('')
const currentWeather = ref(null)
const forecast = ref([])
const weatherAlerts = ref([])
const showNotificationDialog = ref(false)
const showPreviewDialog = ref(false)
const sendingNotification = ref(false)
const notificationFormRef = ref(null)

// 默认通知对象，直接映射到 DeliverymanNotifications
const getDefaultNotification = () => ({
  deliverymanId: null,
  type: 'weather',
  title: '天气提醒',
  message: '',
  relatedEntityId: null
})

const notification = ref(getDefaultNotification())

// 计算属性，判断是否显示 "关联实体ID" 字段
const isRelatedEntityIdVisible = computed(() => {
  return ['new_order', 'task_update'].includes(notification.value.type)
})

// 监听通知类型变化，以设置默认标题和消息
watch(() => notification.value.type, (newType) => {
  const defaultTitles = {
    weather: '天气提醒',
    new_order: '新订单提醒',
    system: '系统通知',
    earnings: '收入提醒',
    task_update: '任务更新'
  }
  notification.value.title = defaultTitles[newType] || '通知'

  // 如果是天气类型，自动填充天气信息
  if (newType === 'weather' && currentWeather.value) {
    const alertText = weatherAlerts.value.length > 0 ? `当前存在${weatherAlerts.value.map(a => a.title).join('、')}。` : ''
    notification.value.message = `紧急通知：${currentWeather.value.city}地区当前天气为${currentWeather.value.weather}，温度${currentWeather.value.temperature}°C。${alertText}请注意安全，合理安排配送时间。`
  } else {
    notification.value.message = ''
  }

  // 如果类型不需要关联ID，则清空
  if (!isRelatedEntityIdVisible.value) {
    notification.value.relatedEntityId = null
  }
})

// 重置表单
const resetNotificationForm = () => {
  notification.value = getDefaultNotification()
  if (notificationFormRef.value) {
    notificationFormRef.value.resetFields()
  }
}

// 发送通知 (已重构)
const sendNotification = async () => {
  if (!notificationFormRef.value) return

  await notificationFormRef.value.validate(async (valid) => {
    if (valid) {
      sendingNotification.value = true
      try {
        // 直接发送与后端 DeliverymanNotifications 实体匹配的 notification 对象
        // isRead 和 createdAt 将由后端处理
        console.log("即将发送到后端的对象:", notification.value)

        const response = await fetch('/adminApi/admin/addWeather', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(notification.value)
        })

        if (!response.ok) {
          const errorResult = await response.json().catch(() => ({}))
          throw new Error(errorResult.message || `HTTP错误，状态码: ${response.status}`)
        }

        ElMessage.success('通知发送成功！')
        showNotificationDialog.value = false

      } catch (error) {
        console.error('发送通知失败:', error)
        ElMessage.error(`发送通知失败: ${error.message}`)
      } finally {
        sendingNotification.value = false
      }
    } else {
      ElMessage.error('请检查表单输入是否完整')
    }
  })
}

// 热门城市列表
const popularCities = ref([
  { name: '北京', adcode: '110000' },
  { name: '上海', adcode: '310000' },
  { name: '广州', adcode: '440100' },
  { name: '深圳', adcode: '440300' },
  { name: '杭州', adcode: '330100' },
  { name: '南京', adcode: '320100' },
  { name: '武汉', adcode: '420100' },
  { name: '成都', adcode: '510100' },
  { name: '西安', adcode: '610100' },
  { name: '重庆', adcode: '500000' }
])

// 高德天气API基础URL
const AMAP_WEATHER_URL = 'https://restapi.amap.com/v3/weather/weatherInfo'

// 计算属性：是否高温
const isHighTemperature = computed(() => {
  if (!currentWeather.value) return false
  return parseInt(currentWeather.value.temperature) >= 35
})

// 获取天气图标
const getWeatherIcon = (weather) => {
  const weatherMap = {
    '晴': '☀️',
    '多云': '⛅',
    '阴': '☁️',
    '小雨': '🌦️',
    '中雨': '🌧️',
    '大雨': '⛈️',
    '暴雨': '🌩️',
    '雷阵雨': '⛈️',
    '小雪': '🌨️',
    '中雪': '❄️',
    '大雪': '☃️',
    '雾': '🌫️',
    '霾': '😷',
    '沙尘暴': '🌪️'
  }
  return weatherMap[weather] || '🌤️'
}

// 检查API密钥是否有效
function checkAPIKey() {
  console.log('当前API密钥:', AMAP_KEY)
  console.log('密钥长度:', AMAP_KEY.length)

  if (!AMAP_KEY || AMAP_KEY.length < 20) {
    ElMessage.error('API密钥无效，请检查配置')
    return false
  }

  return true
}

// 初始化
onMounted(() => {
  if (checkAPIKey()) {
    // 默认获取北京天气
    getWeatherByCity('110000')
  }
})

// 天气预警检测
const checkWeatherAlerts = () => {
  if (!currentWeather.value) return []

  const alerts = []
  const weather = currentWeather.value.weather
  const temperature = parseInt(currentWeather.value.temperature)
  const windpower = currentWeather.value.windpower
  const visibility = parseFloat(currentWeather.value.visibility)

  // 暴雨预警
  if (weather.includes('暴雨') || weather.includes('大雨')) {
    alerts.push({
      type: 'rainstorm',
      title: '🌧️ 暴雨预警',
      message: '当前天气为暴雨，请注意防范积水、山洪等灾害，避免在低洼地带停留。',
      alertType: 'error'
    })
  }

  // 台风预警
  if (weather.includes('台风') || windpower.includes('12') || windpower.includes('11')) {
    alerts.push({
      type: 'typhoon',
      title: '🌀 台风预警',
      message: '当前风力较大，可能受台风影响，请加固室外物品，避免外出。',
      alertType: 'error'
    })
  }

  // 寒潮预警
  if (temperature <= 0) {
    alerts.push({
      type: 'cold',
      title: '❄️ 寒潮预警',
      message: '当前温度较低，请注意保暖，防止感冒，注意道路结冰。',
      alertType: 'warning'
    })
  }

  // 大风预警
  if (windpower.includes('8') || windpower.includes('9') || windpower.includes('10')) {
    alerts.push({
      type: 'strong-wind',
      title: '💨 大风预警',
      message: '当前风力较大，请注意防范高空坠物，避免在广告牌、临时搭建物下停留。',
      alertType: 'warning'
    })
  }

  // 沙尘暴预警
  if (weather.includes('沙尘暴') || weather.includes('扬沙')) {
    alerts.push({
      type: 'sandstorm',
      title: '🌪️ 沙尘暴预警',
      message: '当前为沙尘暴天气，请关闭门窗，外出时佩戴口罩和护目镜。',
      alertType: 'error'
    })
  }

  // 大雾预警
  if (weather.includes('雾') || visibility < 1) {
    alerts.push({
      type: 'fog',
      title: '🌫️ 大雾预警',
      message: '当前能见度较低，请注意交通安全，减速慢行，开启雾灯。',
      alertType: 'warning'
    })
  }

  // 冰雹预警
  if (weather.includes('冰雹')) {
    alerts.push({
      type: 'hail',
      title: '🧊 冰雹预警',
      message: '当前可能出现冰雹天气，请避免外出，注意保护车辆和农作物。',
      alertType: 'error'
    })
  }

  // 雷电预警
  if (weather.includes('雷') || weather.includes('电')) {
    alerts.push({
      type: 'thunder',
      title: '⚡ 雷电预警',
      message: '当前有雷电活动，请避免在空旷地带停留，不要使用金属物品。',
      alertType: 'warning'
    })
  }

  // 高温预警
  if (temperature >= 35) {
    alerts.push({
      type: 'high-temp',
      title: '🌡️ 高温预警',
      message: '当前温度较高，请注意防暑，适当减少户外活动。',
      alertType: 'warning'
    })
  }

  return alerts
}

// 获取单日天气预警
const getDayWeatherAlert = (day) => {
  const weather = day.dayweather
  const nightWeather = day.nightweather
  const dayTemp = parseInt(day.daytemp)
  const nightTemp = parseInt(day.nighttemp)
  const dayPower = day.daypower
  const nightPower = day.nightpower

  // 暴雨预警
  if (weather.includes('暴雨') || weather.includes('大雨') || nightWeather.includes('暴雨') || nightWeather.includes('大雨')) {
    return {
      title: '暴雨',
      icon: '🌧️',
      alertType: 'danger'
    }
  }

  // 台风预警
  if (weather.includes('台风') || dayPower.includes('12') || dayPower.includes('11') || nightPower.includes('12') || nightPower.includes('11')) {
    return {
      title: '台风',
      icon: '🌀',
      alertType: 'danger'
    }
  }

  // 寒潮预警
  if (dayTemp <= 0 || nightTemp <= -5) {
    return {
      title: '寒潮',
      icon: '❄️',
      alertType: 'warning'
    }
  }

  // 大风预警
  if (dayPower.includes('8') || dayPower.includes('9') || dayPower.includes('10') || nightPower.includes('8') || nightPower.includes('9') || nightPower.includes('10')) {
    return {
      title: '大风',
      icon: '💨',
      alertType: 'warning'
    }
  }

  // 沙尘暴预警
  if (weather.includes('沙尘暴') || weather.includes('扬沙') || nightWeather.includes('沙尘暴') || nightWeather.includes('扬沙')) {
    return {
      title: '沙尘暴',
      icon: '🌪️',
      alertType: 'danger'
    }
  }

  // 大雾预警
  if (weather.includes('雾') || nightWeather.includes('雾')) {
    return {
      title: '大雾',
      icon: '🌫️',
      alertType: 'warning'
    }
  }

  // 冰雹预警
  if (weather.includes('冰雹') || nightWeather.includes('冰雹')) {
    return {
      title: '冰雹',
      icon: '🧊',
      alertType: 'danger'
    }
  }

  // 雷电预警
  if (weather.includes('雷') || weather.includes('电') || nightWeather.includes('雷') || nightWeather.includes('电')) {
    return {
      title: '雷电',
      icon: '⚡',
      alertType: 'warning'
    }
  }

  // 高温预警
  if (dayTemp >= 35 || nightTemp >= 35) {
    return {
      title: '高温',
      icon: '🌡️',
      alertType: 'warning'
    }
  }

  return null
}

// 根据城市代码获取天气
const getWeatherByCity = async (adcode) => {
  if (!checkAPIKey()) return

  loading.value = true
  error.value = ''

  try {
    console.log('开始获取天气信息，城市代码:', adcode)

    // 获取实时天气
    const currentResponse = await fetch(`${AMAP_WEATHER_URL}?key=${AMAP_KEY}&city=${adcode}&extensions=base`)
    const currentData = await currentResponse.json()

    console.log('实时天气API响应:', currentData)

    if (currentData.status === '1' && currentData.lives.length > 0) {
      currentWeather.value = currentData.lives[0]
      // 检查天气预警
      weatherAlerts.value = checkWeatherAlerts()
      ElMessage.success('获取实时天气成功')
    } else {
      ElMessage.warning('获取实时天气失败: ' + (currentData.info || '未知错误'))
    }

    // 获取天气预报
    const forecastResponse = await fetch(`${AMAP_WEATHER_URL}?key=${AMAP_KEY}&city=${adcode}&extensions=all`)
    const forecastData = await forecastResponse.json()

    console.log('天气预报API响应:', forecastData)

    if (forecastData.status === '1' && forecastData.forecasts.length > 0) {
      forecast.value = forecastData.forecasts[0].casts
      ElMessage.success('获取天气预报成功')
    } else {
      ElMessage.warning('获取天气预报失败: ' + (forecastData.info || '未知错误'))
    }

  } catch (err) {
    console.error('获取天气信息失败:', err)
    error.value = '获取天气信息失败，请检查网络连接'
    ElMessage.error('网络连接失败: ' + err.message)
  } finally {
    loading.value = false
  }
}

// 搜索城市天气
const searchCityWeather = async () => {
  if (!searchCity.value.trim()) {
    ElMessage.warning('请输入城市名称')
    return
  }

  if (!checkAPIKey()) return

  loading.value = true
  error.value = ''

  try {
    console.log('开始搜索城市:', searchCity.value)

    // 先通过地理编码API获取城市代码
    const geocodeResponse = await fetch(`https://restapi.amap.com/v3/geocode/geo?key=${AMAP_KEY}&address=${encodeURIComponent(searchCity.value)}&city=全国`)
    const geocodeData = await geocodeResponse.json()

    console.log('地理编码API响应:', geocodeData)

    if (geocodeData.status === '1' && geocodeData.geocodes.length > 0) {
      const adcode = geocodeData.geocodes[0].adcode
      await getWeatherByCity(adcode)
      searchCity.value = ''
      ElMessage.success('城市搜索成功')
    } else {
      ElMessage.error('未找到该城市，请检查城市名称')
    }
  } catch (err) {
    console.error('搜索城市失败:', err)
    error.value = '搜索城市失败'
    ElMessage.error('网络连接失败: ' + err.message)
  } finally {
    loading.value = false
  }
}

// 刷新天气
const refreshWeather = () => {
  if (selectedCity.value) {
    getWeatherByCity(selectedCity.value)
  } else {
    getWeatherByCity('110000') // 默认北京
  }
}

// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return ''
  return new Date(timeStr).toLocaleString('zh-CN')
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  const today = new Date()
  const tomorrow = new Date(today)
  tomorrow.setDate(tomorrow.getDate() + 1)

  if (date.toDateString() === today.toDateString()) {
    return '今天'
  } else if (date.toDateString() === tomorrow.toDateString()) {
    return '明天'
  } else {
    return date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' })
  }
}

// 获取预警类型文本
const getAlertTypesText = (alertTypes) => {
  if (alertTypes.includes('all')) return '所有预警'
  const typeMap = {
    'high-temp': '高温预警',
    'rainstorm': '暴雨预警',
    'typhoon': '台风预警',
    'cold': '寒潮预警',
    'strong-wind': '大风预警',
    'sandstorm': '沙尘暴预警',
    'fog': '大雾预警',
    'hail': '冰雹预警',
    'thunder': '雷电预警'
  }
  return alertTypes.map(type => typeMap[type]).join('、')
}

// 获取配送区域文本
const getDeliveryAreasText = (areas) => {
  if (areas.includes('all')) return '全部区域'
  const areaMap = {
    'beijing': '北京市',
    'shanghai': '上海市',
    'guangzhou': '广州市',
    'shenzhen': '深圳市',
    'hangzhou': '杭州市',
    'nanjing': '南京市',
    'wuhan': '武汉市',
    'chengdu': '成都市',
    'xian': '西安市',
    'chongqing': '重庆市'
  }
  return areas.map(area => areaMap[area]).join('、')
}

// 获取通知方式文本
const getNotificationMethodsText = (methods) => {
  const methodMap = {
    'app': 'APP推送',
    'sms': '短信通知',
    'email': '邮件通知',
    'wechat': '微信通知',
    'phone': '电话通知'
  }
  return methods.map(method => methodMap[method]).join('、')
}

// 获取紧急程度文本
const getPriorityText = (priority) => {
  const priorityMap = {
    'low': '普通',
    'medium': '重要',
    'high': '紧急'
  }
  return priorityMap[priority]
}

// 获取发送时间文本
const getSendTimeText = (sendTime, scheduledTime) => {
  if (sendTime === 'now') return '立即发送'
  if (sendTime === 'scheduled' && scheduledTime) {
    return `定时发送：${scheduledTime.toLocaleTimeString()}`
  }
  return '立即发送'
}
</script>

<style scoped>
.weather-container {
  padding: 20px;
  /* 修改为更浅的背景渐变颜色 */
  background: linear-gradient(135deg, #73a6ff 0%, #93bcf9 100%);
  min-height: 100vh;
  position: relative;
  overflow: hidden;
}

.weather-background {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
}

.clouds {
  position: absolute;
  width: 100%;
  height: 100%;
}

.cloud {
  position: absolute;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 50px;
  animation: float 6s ease-in-out infinite;
}

.cloud1 {
  width: 100px;
  height: 40px;
  top: 20%;
  left: 10%;
  animation-delay: 0s;
}

.cloud2 {
  width: 80px;
  height: 30px;
  top: 40%;
  right: 15%;
  animation-delay: 2s;
}

.cloud3 {
  width: 120px;
  height: 50px;
  top: 60%;
  left: 20%;
  animation-delay: 4s;
}

@keyframes float {
  0%, 100% { transform: translateY(0px); }
  50% { transform: translateY(-20px); }
}

.weather-card {
  max-width: 1200px;
  margin: 0 auto;
  border-radius: 20px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  background: rgba(255, 255, 255, 0.95);
  position: relative;
  z-index: 1;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 0;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.weather-icon {
  font-size: 49px;
  animation: bounce 2s infinite;
}

@keyframes bounce {
  0%, 20%, 50%, 80%, 100% { transform: translateY(0); }
  40% { transform: translateY(-10px); }
  60% { transform: translateY(-5px); }
}

.card-header h2 {
  margin: 0;
  color: #333;
  font-weight: 600;
  font-size: 36px;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.notification-btn {
  border-radius: 20px;
  padding: 8px 16px;
  font-size: 12px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.notification-btn .el-icon {
  margin-right: 4px;
}

.notification-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(255, 152, 0, 0.3);
}

.notification-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.refresh-btn {
  border-radius: 25px;
  padding: 10px 20px;
  font-weight: 500;
}

.city-selector {
  margin-bottom: 30px;
}

.search-input, .city-select {
  border-radius: 25px;
}

.search-btn {
  border-radius: 0 25px 25px 0;
}

.current-weather {
  background: linear-gradient(135deg, #74b9ff 0%, #0984e3 100%);
  border-radius: 20px;
  padding: 30px;
  color: white;
  margin-bottom: 30px;
  box-shadow: 0 10px 30px rgba(116, 185, 255, 0.3);
}

.weather-main {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.location-info {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.location-icon {
  font-size: 24px;
  margin-bottom: 5px;
}

.location-info h3 {
  margin: 0;
  font-size: 45px;
  font-weight: 600;
}

.update-time {
  margin: 0;
  opacity: 0.9;
  font-size: 21px;
}

.temperature-section {
  text-align: right;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 10px;
}

.weather-icon-large {
  font-size: 48px;
  margin-bottom: 10px;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.1); }
  100% { transform: scale(1); }
}

.current-temp {
  font-size: 4rem;
  font-weight: bold;
  margin-bottom: 5px;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
}

.weather-desc {
  font-size: 1.3rem;
  margin-bottom: 10px;
  font-weight: 500;
}

.temp-range {
  font-size: 1.2rem;
  display: flex;
  gap: 10px;
  align-items: center;
}

.low-temp {
  color: #74b9ff;
  font-weight: 600;
}

.temp-separator {
  opacity: 0.7;
  font-size: 1rem;
}

.high-temp {
  color: #ff7675;
  font-weight: 600;
}

.weather-alerts {
  margin-bottom: 20px;
}

.alert-item {
  margin-bottom: 15px;
}

.weather-alert-item {
  border-radius: 15px;
  border: none;
  font-weight: 500;
}

.weather-alert-item p {
  margin: 5px 0 0 0;
  font-size: 14px;
  line-height: 1.5;
}

.weather-alert {
  margin-bottom: 20px;
}

.high-temp-alert {
  border-radius: 15px;
  border: none;
}

.weather-details {
  margin-top: 20px;
}

.detail-item {
  text-align: center;
  padding: 20px;
  background: rgba(255, 255, 255, 0.15);
  border-radius: 15px;
  margin-bottom: 10px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  transition: transform 0.3s ease;
}

.detail-item:hover {
  transform: translateY(-5px);
}

.detail-icon {
  font-size: 43px;
  margin-bottom: 10px;
}

.detail-label {
  font-size: 19px;
  opacity: 0.9;
  margin-bottom: 8px;
  font-weight: 500;
}

.detail-value {
  font-size: 24px;
  font-weight: 600;
}

.forecast-section {
  margin-top: 30px;
}

.forecast-header {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 25px;
}

.forecast-icon {
  font-size: 24px;
}

.forecast-section h3 {
  margin: 0;
  color: #333;
  font-weight: 600;
  font-size: 20px;
}

.forecast-container {
  display: flex;
  gap: 20px;
  overflow-x: auto;
  padding-bottom: 15px;
}

.forecast-item {
  flex: 1;
  min-width: 140px;
  background: white;
  border-radius: 20px;
  padding: 25px 20px;
  text-align: center;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  position: relative;
  border: 1px solid rgba(0, 0, 0, 0.05);
}

.forecast-item:hover {
  transform: translateY(-8px);
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.15);
}

.forecast-date {
  font-weight: 600;
  color: #333;
  margin-bottom: 15px;
  font-size: 23px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.date-icon {
  font-size: 16px;
}

.forecast-weather-icon {
  font-size: 46px;
  margin-bottom: 10px;
  animation: float 3s ease-in-out infinite;
}

.forecast-weather {
  color: #666;
  margin-bottom: 12px;
  font-size: 22px;
  font-weight: 500;
}

.forecast-temp-range {
  margin-bottom: 10px;
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.forecast-high {
  color: #e74c3c;
  font-weight: 600;
  font-size: 22px;
}

.forecast-low {
  color: #3498db;
  font-weight: 600;
  font-size: 22px;
}

.forecast-wind {
  font-size: 19px;
  color: #999;
  margin-bottom: 10px;
}

.forecast-alert {
  position: absolute;
  top: 15px;
  right: 15px;
}

.high-temp-tag {
  border-radius: 15px;
  font-weight: 600;
}

.weather-alert-tag {
  border-radius: 15px;
  font-weight: 600;
  font-size: 12px;
}

@media (max-width: 768px) {
  .weather-container {
    padding: 10px;
  }

  .weather-main {
    flex-direction: column;
    text-align: center;
    gap: 20px;
  }

  .temperature-section {
    text-align: center;
    align-items: center;
  }

  .current-temp {
    font-size: 3rem;
  }

  .forecast-container {
    flex-direction: column;
  }

  .forecast-item {
    min-width: auto;
  }

  .card-header {
    flex-direction: column;
    gap: 15px;
  }

  .header-left {
    justify-content: center;
  }
}

.preview-content {
  padding: 20px;
}

.preview-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.preview-icon {
  font-size: 24px;
}

.preview-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.preview-message {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 15px;
  line-height: 1.6;
  color: #333;
}

.preview-info p {
  margin: 8px 0;
  color: #666;
  font-size: 14px;
}

.preview-info strong {
  color: #333;
}

/* 创建通知对话框新样式 */
.create-notification-dialog .el-dialog {
  border-radius: 20px;
  overflow: hidden;
  box-shadow: 0 25px 50px rgba(0, 0, 0, 0.15);
  border: none;
}

.create-notification-dialog .el-dialog__header {
  display: none;
}

.create-notification-dialog .el-dialog__body {
  padding: 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow: hidden;
}

.create-notification-dialog .el-dialog__body::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="25" cy="25" r="1" fill="rgba(255,255,255,0.1)"/><circle cx="75" cy="75" r="1" fill="rgba(255,255,255,0.1)"/><circle cx="50" cy="10" r="0.5" fill="rgba(255,255,255,0.1)"/><circle cx="10" cy="60" r="0.5" fill="rgba(255,255,255,0.1)"/><circle cx="90" cy="40" r="0.5" fill="rgba(255,255,255,0.1)"/></pattern></defs><rect width="100" height="100" fill="url(%23grain)"/></svg>');
  pointer-events: none;
}

.notification-form-styled {
  padding: 40px;
  position: relative;
  z-index: 1;
}

.notification-form-styled .el-form-item {
  margin-bottom: 28px;
  position: relative;
}

.notification-form-styled .el-form-item__label {
  font-size: 15px;
  font-weight: 600;
  color: rgba(255, 255, 255, 0.95);
  padding-bottom: 10px !important;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  letter-spacing: 0.5px;
}

/* 统一输入框/选择框样式 */
.notification-form-styled .el-input__wrapper,
.notification-form-styled .el-select__wrapper,
.notification-form-styled .el-input-number {
  border-radius: 12px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1) !important;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  padding: 8px 12px;
  border: 2px solid transparent;
}

.notification-form-styled .el-input__wrapper:hover,
.notification-form-styled .el-select__wrapper:hover,
.notification-form-styled .el-input-number:hover {
  background: rgba(255, 255, 255, 1);
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15) !important;
}

.notification-form-styled .el-input__wrapper.is-focus,
.notification-form-styled .el-select__wrapper.is-focused {
  background: rgba(255, 255, 255, 1);
  box-shadow: 0 0 0 3px rgba(255, 255, 255, 0.3) !important;
  border-color: rgba(255, 255, 255, 0.5);
}

.notification-form-styled .el-textarea__inner {
  border-radius: 12px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1) !important;
  border: 2px solid transparent;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  padding: 12px;
  min-height: 120px;
}

.notification-form-styled .el-textarea__inner:focus {
  background: rgba(255, 255, 255, 1);
  box-shadow: 0 0 0 3px rgba(255, 255, 255, 0.3) !important;
  border-color: rgba(255, 255, 255, 0.5);
  transform: translateY(-2px);
}

/* 图标样式 */
.notification-form-styled .el-input__prefix,
.notification-form-styled .el-textarea__prefix {
  color: #667eea;
  font-size: 16px;
  margin-right: 8px;
}

/* 占位符样式 */
.notification-form-styled .el-input__inner::placeholder,
.notification-form-styled .el-textarea__inner::placeholder {
  color: rgba(102, 126, 234, 0.6);
  font-weight: 500;
}

/* 底部按钮样式 */
.create-notification-dialog .el-dialog__footer {
  padding: 0;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-top: 1px solid rgba(255, 255, 255, 0.2);
}

.dialog-footer-styled {
  display: flex;
  justify-content: flex-end;
  gap: 15px;
  padding: 25px 40px;
}

.dialog-footer-styled .send-btn {
  border-radius: 12px;
  font-weight: 600;
  padding: 12px 28px;
  height: auto;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  color: white;
  font-size: 15px;
  letter-spacing: 0.5px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
}

.dialog-footer-styled .send-btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.5);
  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
}

.dialog-footer-styled .send-btn:active {
  transform: translateY(-1px);
}

.dialog-footer-styled .send-btn .el-icon {
  margin-right: 8px;
  font-size: 16px;
}

.dialog-footer-styled .cancel-btn {
  border-radius: 12px;
  font-weight: 600;
  padding: 12px 28px;
  height: auto;
  background: rgba(255, 255, 255, 0.9);
  border: 2px solid rgba(255, 255, 255, 0.3);
  color: #667eea;
  font-size: 15px;
  letter-spacing: 0.5px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  backdrop-filter: blur(10px);
}

.dialog-footer-styled .cancel-btn:hover {
  background: rgba(255, 255, 255, 1);
  border-color: rgba(255, 255, 255, 0.5);
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.dialog-footer-styled .cancel-btn .el-icon {
  margin-right: 8px;
  font-size: 16px;
}

/* 选择框选项样式 */
.notification-form-styled .el-select-dropdown {
  border-radius: 12px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
  border: none;
  overflow: hidden;
  z-index: 9999;
}

.notification-form-styled .el-select-dropdown__item {
  padding: 12px 20px;
  transition: all 0.2s ease;
  cursor: pointer;
  display: flex;
  align-items: center;
}

.notification-form-styled .el-select-dropdown__item:hover {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.notification-form-styled .el-select-dropdown__item.is-selected {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-weight: 600;
}

/* 确保选择框下拉菜单在最上层 */
.el-select__popper {
  z-index: 9999 !important;
}

.el-select-dropdown {
  z-index: 9999 !important;
}

/* 数字输入框样式 */
.notification-form-styled .el-input-number__decrease,
.notification-form-styled .el-input-number__increase {
  background: rgba(102, 126, 234, 0.1);
  border: none;
  color: #667eea;
  transition: all 0.2s ease;
}

.notification-form-styled .el-input-number__decrease:hover,
.notification-form-styled .el-input-number__increase:hover {
  background: rgba(102, 126, 234, 0.2);
  color: #5a6fd8;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .notification-form-styled {
    padding: 25px;
  }
  
  .dialog-footer-styled {
    padding: 20px 25px;
    flex-direction: column;
  }
  
  .dialog-footer-styled .send-btn,
  .dialog-footer-styled .cancel-btn {
    width: 100%;
    justify-content: center;
  }
}
</style>

